/*
 * @# UserFileUtils.java 2011-12-29 下午06:58:14
 * 
 * Copyright (C) 2010 - 2011 广州羿安信息科技有限公司
 * Guangzhou ianswer information technology co. ltd.
 * 
 * All rights reserved!
 */
package com.ianswer.px.utils;

import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;

/**
 * 用户目录.
 * 
 * <pre>
 * 用户目录结构定义： /一级目录/二级目录/三级目录/日期目录(月份)
 * </pre>
 * 
 * @author alvin hwang
 */
public class UserFileUtils {

	/**
	 * 用于生成文件名中的随机串部分
	 */
	private static final String RANDOM_STR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
	private static final int RANDOM_STR_LENGTH = 5;

	private static final String FILE_SP = "/";
	private static final int MAX_DIRECTORY = 300;

	private UserFileUtils() {
		// empty!
	}

	/**
	 * 获取file在服务器里的存储路径.
	 * 
	 * @param userId
	 *            用户标识.
	 * @param filename
	 *            上传的文件名(含扩展名)
	 * @return file在服务器里的存储路径.
	 */
	public static String file(Long userId, String filename) {
		return dir(userId) + genFileName(filename);
	}

	public static String dir(Long userId) {
		return getUserDirBase(userId);
	}

	/**
	 * 上传文件时生成文件名<br>
	 * 规则： md5Hex(文件名 + 当前时间毫秒数 + 5位随机串 ) + "." + 扩展名.
	 * 
	 * @param filename
	 *            上传的文件名(含扩展名)
	 * @return
	 */
	public static String genFileName(String filename) {
		String name = FilenameUtils.getBaseName(filename) + System.currentTimeMillis()
				+ RandomStringUtils.random(RANDOM_STR_LENGTH, RANDOM_STR);
		return DigestUtils.md5Hex(name.getBytes()) + "." + FilenameUtils.getExtension(filename);
	}

	private static String getUserDirBase(Long userId) {
		if (null == userId || userId <= 0) {
			return StringUtils.EMPTY;
		}
		StringBuilder dir = new StringBuilder();
		dir.append(FILE_SP);
		dir.append(getFirstDirName(userId));
		dir.append(FILE_SP);
		dir.append(getSecondDirName(userId));
		dir.append(FILE_SP);
		dir.append(getThirdDirName(userId));
		dir.append(FILE_SP);
		dir.append(DateFormatUtils.format(new Date(), "yyyyMM"));
		dir.append(FILE_SP);
		return dir.toString();
	}

	private static String getFirstDirName(Long userId) {
		if (null == userId || userId <= 0) {
			return StringUtils.EMPTY;
		}
		return String.valueOf(userId / (MAX_DIRECTORY * MAX_DIRECTORY));
	}

	private static String getSecondDirName(Long userId) {
		if (null == userId || userId <= 0) {
			return StringUtils.EMPTY;
		}
		return String.valueOf(userId / (MAX_DIRECTORY));
	}

	private static String getThirdDirName(Long userId) {
		if (null == userId || userId <= 0) {
			return StringUtils.EMPTY;
		}
		return String.valueOf(userId);
	}

}
